package com.sqlcheck.controller;

import com.sqlcheck.common.response.ApiResponse;
import com.sqlcheck.dto.request.UnifiedAnalysisRequest;
import com.sqlcheck.dto.request.FormatSqlRequest;
import com.sqlcheck.dto.request.ValidateSqlRequest;
import com.sqlcheck.dto.response.UnifiedAnalysisResponse;
import com.sqlcheck.dto.response.SqlExampleResponse;
import com.sqlcheck.dto.response.FormatSqlResponse;
import com.sqlcheck.dto.response.DatabaseTypeResponse;
import com.sqlcheck.service.UnifiedAnalysisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/analysis")
@RequiredArgsConstructor
@Validated
@Tag(name = "统一分析", description = "统一SQL兼容性分析相关接口")
@Deprecated // 暂时关闭SQL在线分析功能
public class AnalysisController {

    private final UnifiedAnalysisService unifiedAnalysisService;

    @PostMapping("/unified")
    @Operation(summary = "统一SQL分析", description = "统一的SQL兼容性分析接口，支持规则分析和LLM分析")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "分析成功", content = @Content(schema = @Schema(implementation = UnifiedAnalysisResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "请求参数错误", content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "服务器内部错误", content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @Deprecated // 暂时关闭
    public ResponseEntity<ApiResponse<UnifiedAnalysisResponse>> performUnifiedAnalysis(
            @Valid @RequestBody @Parameter(description = "统一分析请求") UnifiedAnalysisRequest request) {

        // 暂时关闭功能，返回维护中信息
        return ResponseEntity.ok(ApiResponse.error(
            "503", 
            "SQL在线分析功能暂时关闭维护中，请稍后再试"
        ));

        /* 原有实现已暂时注释
        try {
            log.info("收到统一分析请求，源数据库: {}, 目标数据库: {}, AI增强: {}",
                    request.getSourceDbType(), request.getTargetDbType(), request.isAiEnhancementEnabled());

            // 统一使用分层分析逻辑
            UnifiedAnalysisResponse result = unifiedAnalysisService.performLayeredAnalysis(request);

            log.info("统一分析完成，发现 {} 个兼容性问题", result.getStatistics().getTotalIssues());
            return ResponseEntity.ok(ApiResponse.success(result));

        } catch (IllegalArgumentException e) {
            log.warn("统一分析请求参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("请求参数错误: " + e.getMessage()));

        } catch (Exception e) {
            log.error("统一分析失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("分析过程中发生错误: " + e.getMessage()));
        }
        */
    }

    @GetMapping("/databases")
    @Operation(summary = "获取支持的数据库类型", description = "获取系统支持的所有数据库类型列表")
    public ResponseEntity<ApiResponse<List<DatabaseTypeResponse>>> getSupportedDatabases() {
        try {
            log.debug("获取支持的数据库类型列表");

            List<DatabaseTypeResponse> databases = unifiedAnalysisService.getSupportedDatabases();

            return ResponseEntity.ok(ApiResponse.success(databases));

        } catch (Exception e) {
            log.error("获取数据库类型列表失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("获取数据库类型列表失败: " + e.getMessage()));
        }
    }

    @GetMapping("/sql-examples")
    @Operation(summary = "获取SQL示例", description = "获取SQL示例列表，支持按分类和数据库类型过滤")
    public ResponseEntity<ApiResponse<List<SqlExampleResponse>>> getSqlExamples(
            @Parameter(description = "示例分类") @RequestParam(required = false) String category,
            @Parameter(description = "源数据库类型") @RequestParam(required = false) String sourceDbType) {

        try {
            log.debug("获取SQL示例，分类: {}, 数据库类型: {}", category, sourceDbType);

            List<SqlExampleResponse> examples = unifiedAnalysisService.getSqlExamples(category, sourceDbType);

            return ResponseEntity.ok(ApiResponse.success(examples));

        } catch (Exception e) {
            log.error("获取SQL示例失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("获取SQL示例失败: " + e.getMessage()));
        }
    }

    @PostMapping("/format")
    @Operation(summary = "格式化SQL", description = "格式化SQL语句")
    public ResponseEntity<ApiResponse<FormatSqlResponse>> formatSql(
            @Valid @RequestBody @Parameter(description = "SQL格式化请求") FormatSqlRequest request) {

        try {
            log.debug("格式化SQL，数据库类型: {}", request.getDbType());

            FormatSqlResponse result = unifiedAnalysisService.formatSql(request.getSqlContent(), request.getDbType());

            return ResponseEntity.ok(ApiResponse.success(result));

        } catch (IllegalArgumentException e) {
            log.warn("格式化SQL请求参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("请求参数错误: " + e.getMessage()));

        } catch (Exception e) {
            log.error("格式化SQL失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("格式化SQL失败: " + e.getMessage()));
        }
    }

    @PostMapping("/validate")
    @Operation(summary = "验证SQL语法", description = "验证SQL语法是否正确")
    public ResponseEntity<ApiResponse<Boolean>> validateSqlSyntax(
            @Valid @RequestBody @Parameter(description = "SQL验证请求") ValidateSqlRequest request) {

        try {
            log.debug("验证SQL语法，数据库类型: {}", request.getDbType());

            boolean isValid = unifiedAnalysisService.validateSqlSyntax(request.getSqlContent(), request.getDbType());

            return ResponseEntity.ok(ApiResponse.success(isValid));

        } catch (Exception e) {
            log.error("验证SQL语法失败", e);
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("验证SQL语法失败: " + e.getMessage()));
        }
    }

}